package handlers

import (
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"lemon-duck-tea/cache"
	"lemon-duck-tea/model"
	"lemon-duck-tea/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "redis_err_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误3次，禁止登录",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username = ?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.Password != pkg.Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "密码错误3次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}

func AddRolenode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func UserRole(c *gin.Context) {
	uid := c.Query("uid")
	var role []model.Role
	/*
		SELECT * FROM roles
		LEFT JOIN user_roles on user_roles.rid=roles.id
		WHERE user_roles.uid = 1
	*/
	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles on user_roles.rid=roles.id").Where("user_roles.uid=?", uid).
		Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})
	return
}

func RoleNode(c *gin.Context) {
	rid := c.Query("rid")
	var node []model.Node
	/*
		SELECT * FROM nodes
		LEFT JOIN role_nodes on role_nodes.nid=nodes.id
		WHERE role_nodes.rid = 1
	*/
	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes on role_nodes.nid=nodes.id").Where("role_nodes.rid=?", rid).
		Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": node,
	})
	return
}

func AddCar(c *gin.Context) {
	car_code := c.PostForm("car_code")
	car_name := c.PostForm("car_name")
	car_price, _ := strconv.Atoi(c.PostForm("car_price"))
	data := model.Car{
		CarCode:  car_code,
		CarName:  car_name,
		CarPrice: car_price,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func AddCarOrder(c *gin.Context) {
	cid, _ := strconv.Atoi("cid")
	order_code := c.PostForm("order_name")
	order_name := c.PostForm("order_name")
	order_num, _ := strconv.Atoi(c.PostForm("order_num"))
	data := model.CarOrder{
		Cid:       cid,
		OrderCode: order_code,
		OrderName: order_name,
		OrderNum:  order_num,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var list []model.CarOrderList
	redis_key := "redis_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("car_orders").Select(
			"car_orders.id as CarOrderId",
			"cars.car_code as CarCode",
			"cars.car_name as CarName",
			"cars.car_price as CarPrice",
			"car_orders.order_code as OrderCode",
			"car_orders.order_name as OrderName",
			"car_orders.order_num as OrderNum",
		).
			Joins("LEFT JOIN cars ON cars.id=car_orders.cid").
			Offset(offset).
			Limit(size).
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*3)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	/*
		SELECT
		car_orders.id as CarOrderId,
		cars.car_code as CarCode,
		cars.car_name as CarName,
		cars.car_price as CarPrice,
		car_orders.order_code as OrderCode,
		car_orders.order_name as OrderName,
		car_orders.order_num as OrderNum
		FROM
		car_orders
		LEFT JOIN cars ON cars.id=car_orders.cid
	*/

	var count int64
	model.DB.Model(&model.CarOrder{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  list,
		"count": count,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var list []model.CarOrderList
	redis_key := "redis_del_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("car_orders").Select(
			"car_orders.id as CarOrderId",
			"cars.car_code as CarCode",
			"cars.car_name as CarName",
			"cars.car_price as CarPrice",
			"car_orders.order_code as OrderCode",
			"car_orders.order_name as OrderName",
			"car_orders.order_num as OrderNum",
		).
			Joins("LEFT JOIN cars ON cars.id=car_orders.cid").Where("car_orders.cid = ?", id).
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*3)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	/*
		SELECT
		car_orders.id as CarOrderId,
		cars.car_code as CarCode,
		cars.car_name as CarName,
		cars.car_price as CarPrice,
		car_orders.order_code as OrderCode,
		car_orders.order_name as OrderName,
		car_orders.order_num as OrderNum
		FROM
		car_orders
		LEFT JOIN cars ON cars.id=car_orders.cid
	*/

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return

}
